import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button } from 'antd';
import React, { useRef, useState } from 'react';
import { Link, useHistory } from 'react-router-dom';

import { IMenu } from '@/models/user';
import { getMenus } from '@/services/system/menu';
import { expandedRender, flatToNest } from '@/utils';

const Menu: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const history = useHistory();

  const columns: ProColumns<IMenu>[] = [
    {
      title: '名称',
      dataIndex: 'title',
      render: (_, record) => <Link to={`/system/menu/detail/${record.id}`}>{_}</Link>,
    },
    { title: 'code', dataIndex: 'code' },
    { title: '路径', dataIndex: 'path' },
    { title: '重定向', dataIndex: 'redirect', search: false },
    { title: '图标', dataIndex: 'icon', search: false },
    {
      title: '是否展示',
      dataIndex: 'show',
      search: false,
      render: (v) => (v ? '是' : '否'),
    },
  ];

  const [tableData, setTableData] = useState([]);

  return (
    <ProTable
      actionRef={actionRef}
      pagination={false}
      columns={columns}
      request={async (params) => {
        const { data } = await getMenus(params);
        const tree = flatToNest(data);
        setTableData(tree);
        return {
          data: tree,
          success: true,
        };
      }}
      rowKey="id"
      expandable={{
        expandedRowKeys: expandedRender(tableData),
      }}
      options={{ fullScreen: true, reload: false, density: false }}
      toolBarRender={() => [
        <Button key="add" type="primary" onClick={() => history.push('/system/menu/add')}>
          <PlusOutlined />
          新建菜单
        </Button>,
      ]}
    />
  );
};

export default Menu;
